#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>

#include "./Log.hpp"

using namespace ns_log;

const int default_port = 0;

class UdpServer
{
public:
    UdpServer(int port = default_port)
        :_port(port)
    {}
    ~UdpServer()
    {}

    bool Init()
    {
        int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(sockfd < 0)
        {
            LOG(ERROR) << "创建套接字失败" << std::endl;
            return false;
        }

        _sockfd = sockfd;

        struct sockaddr_in load;
        memset(&load, 0, sizeof(load));
        load.sin_family = AF_INET;
        load.sin_addr.s_addr = INADDR_ANY;
        load.sin_port = htons(_port);

        int ret = ::bind(_sockfd, (sockaddr *)&load, sizeof(load));
        if(ret != 0)
        {
            LOG(ERROR) << "绑定套接字失败" << std::endl;
            return false;
        }   

        return true;
    }

    void Start()
    {
        char buffer[1024];
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            int size = recvfrom(_sockfd, &buffer, sizeof(buffer), 0, (sockaddr *)&peer, &len);
            if(size > 0)
            {
                buffer[size] = 0;
                LOG(INFO) << "[" << peer.sin_addr.s_addr << ":" << peer.sin_port << "]: " << buffer << std::endl;
                sendto(_sockfd, buffer, sizeof(buffer), 0, (sockaddr *)&peer, len); 
            }
            else
            {
                LOG(WARNING) << "接受消息失败" << std::endl;
            }
        }
    }
private:
    int _port;
    int _sockfd;
};